/**
 * Created by majunpeng on 2017/4/7.
 */
$(function () {
	//
	tsUtils.setIframeHeight();
	//初始化部门树
	initDept();
});

/**
 * 初始化部门树
 */
function initDept() {
	var setting = {
		data: {
			key: {
				name: "FNAME"
			},
			simpleData: {
				enable: true
				,idKey: "FCODE",
				pIdKey: "FPARENT",
				rootPId: ""
			}
		},
		view:{
			showLine: false
			,showIcon: true
		}
		,callback: {
			onClick: clickDeptTree
		}
	};

	var deptSetting = {
		data: {
			key: {
				name: "FNAME"
			},
			simpleData: {
				enable: true
				,idKey: "FCODE",
				pIdKey: "FPARENT",
				rootPId: ""
			}
		},
		view:{
			showLine: false
			,showIcon: true
		}
		,callback: {
			onClick: function onClick(event, treeId, treeNode) {
				$('#FDEPTNAME').val(treeNode.FNAME);
				$('#FDEPTCODE').val(treeNode.FCODE);
				$('#FORGCODE').val(treeNode.FORGCODE);
			}
		}
	};

	var rangeDeptSetting = {
		data: {
			key: {
				name: "FNAME"
			},
			simpleData: {
				enable: true
				,idKey: "FCODE",
				pIdKey: "FPARENT",
				rootPId: ""
			}
		},
		view:{
			showLine: false
			,showIcon: true
		}
		,callback: {
			onClick: function onClick(event, treeId, treeNode) {
				$('#FDATARANGENAME').val(treeNode.FNAME);
				$('#FDATARANGE').val(treeNode.FCODE);
			}
		}
	};

	var zTreeObj;	//tree 对象
	$.ajax({
		url:tsUtils.getRootPath()+"/public/getDeptJson"
		,method:"post"
		,contentType:"application/x-www-form-urlencoded"
		,success: function(r) {
			var obj=r.msg;
			if(obj==""||obj==undefined||obj==null){
				sysObj['dept'] = r.rows;
				zTreeObj = $.fn.zTree.init($("#userTree"), setting, r.rows);
				$.fn.zTree.init($('#dept-tree'),deptSetting,r.rows);
				$.fn.zTree.init($('#range-dept-tree'),rangeDeptSetting,r.rows);
				//默认展开节点
				var initNode = zTreeObj.getNodes()[0];
				if(initNode.children.length>0){
					initNode=initNode.children[0];
				}
				zTreeObj.selectNode(initNode,false,true);
				loadData(initNode.FCODE);
			}else{
				layer.alert(r.msg);
			}
		}
		,error:function (req,status,e) {
			layer.alert(e.toString());
		}
	});


}

/**
 * 部门树点击事件
 * @param event
 * @param treeId
 * @param treeNode
 */
function clickDeptTree(event, treeId, treeNode) {
	sysObj.deptCode = treeNode.FCODE;
	$('#userTable').bootstrapTable('refresh'
		,{
			url:tsUtils.getRootPath()+'/user/userList'
			,contentType:"application/x-www-form-urlencoded",
			queryParams:function (params) {
				params["where"]=treeNode.FCODE;
				return params;
			}
		});
}

/**
 * 加载表格数据
 * @param selectKey
 */
function loadData(selectKey) {
	var height = $('.table-container').height();
	console.log(height);
	$('#userTable').bootstrapTable({
		url				:tsUtils.getRootPath()+'/user/userList',
		method			:'post',
		striped			:true,					//是否显示间隔栏颜色
		pagination		:true,					//是否分页
		sortable		:false,					//是否启用排序
		pageNumber		:1,
		pageSize		:5,
		pageList		:[5,10,15,20],
		sidePagination	:'server',
		contentType		:"application/x-www-form-urlencoded",
		queryParamsType	:'',
		height			:height,
		columns		:[{
			title:'选中',
			field:'state',
			checkbox:true,
		},{
			field:'FROWNUM',
			title:'序号',
			align:'center',
			width:40
		},{
			field:'FCODE',
			title:'用户代码',
			align:'center',
			width:60
		},{
			field:'FNAME',
			title:'用户名称',
			align:'center',
			width:60,

		},{
			field:'FLOGINCODE',
			title:'登陆名',
			align:'center',
			width:60
		},{
			field:'FDEPTNAME',
			title:'所属机构',
			width:400,
			align:'center'
		},{
			field:'FISSTOP',
			title:'是否停用',
			width:20,
			align:'center'
		}],
		queryParams :queryParams,
		onDblClickCell:function (field,value,row,td) {
			console.log(row);
		},
		onLoadSuccess:function (data) {

		},
		onLoadError:function (data) {
			tsUtils.handleError(data);
		}
	});

	//表格初始化查询参数
	function queryParams(params) {
		var ztree=$.fn.zTree.getZTreeObj("userTree");
		var nodes=ztree.getSelectedNodes();
		if(nodes && nodes!=null){
			var selectKey=nodes[0].FCODE;
			params["where"]=selectKey;
			params["pageSize"]=params.pageSize;
			params["pageNumber"]=params.pageNumber;
		}
		return params;
	}
}

/**
 * 添加用户
 */
function addUser(){
	$('#add-content form')[0].reset();
	$('#add-content form :input').attr('value','');
	$('#FCODE').attr('readonly',false);
	layer.open({
		type:1,
		title:'用户-添加',
		area:['600px','400px'],
		skin:'layer-window',
		shadeClose:true,
		content:$('#add-content'),
		btn:['添加','取消'],
		yes:function () {
			postData('add');
		}
	})
}

function editUser(){
	var selectArray;
	selectArray = $('#userTable').bootstrapTable('getSelections');
	if(selectArray.length >1){
		layer.alert('只能修改一项',{icon:6})
	}else{
		getUserInfo(selectArray[0].FCODE);
	}
}

/**
 * 获取用户信息
 * @param fcode
 */
function getUserInfo(fcode) {
	var data = {};
	data.fcode = fcode;
	$.ajax({
		type:'post',
		url:tsUtils.getRootPath()+'/user/getUserInfo',
		data:JSON.stringify(data),
		contentType:'application/json;charset=utf-8',
		success:function (datas) {
			doEdit(datas.rows)
		}
	});
}

function doEdit(data) {
	sysForm.setForm(data[0]);
	$('#FCODE').attr('readonly',true);
	$('#FPASSWORD').attr('readonly',true);
	$('#FCONFIRMPASSWORD').attr('readonly',true);
	// setForm(data);
	layer.open({
		type:1,
		title:'人员-修改',
		area:['600px','400px'],
		skin:'layer-window',
		shadeClose:true,
		content:$('#add-content'),
		btn:['修改','取消'],
		yes:function () {
			postData('edit');
		}
	})
}

/**
 * 下拉一系列方法
 */
function showMenu() {
	var deptObj = $('#FDEPTNAME');
	var deptOffset = $('#FDEPTNAME').offset();
	$('#deptTree').css({left:deptOffset.left+'px',top:deptOffset.top + deptObj.outerHeight()+'px'}).slideDown('fast');
	$('body').bind('mousedown',onBodyDown);
}

function showMenu2() {
	var deptObj = $('#FDATARANGENAME');
	var deptOffset = $('#FDATARANGENAME').offset();
	$('#rangeDeptTree').css({left:deptOffset.left+'px',top:deptOffset.top + deptObj.outerHeight()+'px'}).slideDown('fast');
	$('body').bind('mousedown',onBodyDown2);
}

function hideMenu() {
	$('#deptTree').fadeOut('fast');
	$('#rangeDeptTree').fadeOut('fast');
	$('body').unbind('mousedown',onBodyDown);
	$('body').unbind('mousedown',onBodyDown2);
}


function onBodyDown(event) {
	if(!(event.target.id == 'menuBtn' || event.target.id == 'deptTree' || $(event.target).parents('#deptTree').length > 0 )){
		hideMenu();
	}
}

function onBodyDown2(event) {
	if(!(event.target.id == 'menuBtn2' || event.target.id == 'rangeDeptTree' || $(event.target).parents('#rangeDeptTree').length > 0 )){
		hideMenu();
	}
}

/**
 * 提交人员参数
 * @param type
 */
function postData(type) {
	var formData = sysForm.getFormData('addUserForm');
	var url;
	if(type == 'add'){
		url = tsUtils.getRootPath()+'/user/addUser';
	}else if(type == 'edit'){
		url = tsUtils.getRootPath()+'/user/editUser';
	}

	$.ajax({
		type:'post',
		url:url,
		data:JSON.stringify(formData),
		contentType:'application/json;charset=utf-8',
		success:function (data) {
			layer.closeAll();
			if(type == 'add'){
				layer.msg('添加成功',{time:1500});
			}else{
				layer.msg('修改成功',{time:1500});
			}
			var treeObj = $.fn.zTree.getZTreeObj('userTree');
			var node = treeObj.getNodeByParam('FCODE',$('#FDEPTCODE').val());
			treeObj.selectNode(node);
			sysObj.deptCode = $('#FDEPTCODE').val();
			$('#userTable').bootstrapTable('refresh'
				,{
					url:tsUtils.getRootPath()+'/user/userList'
					,contentType:"application/x-www-form-urlencoded",
					queryParams:function (params) {
						params["where"]=$('#FDEPTCODE').val();
						return params;
					}
				});

		},
		error:function (data) {
			layer.closeAll();
			if(type == 'add'){
				layer.msg('添加失败',{time:1500});
			}else{
				layer.msg('修改失败',{time:1500});
			}
		}
	})
}

function deleteUser() {
	var selectArray;
	selectArray = $('#userTable').bootstrapTable('getSelections');
	if(selectArray.length == 0){
		layer.alert('请选择删除项',{icon:6})
	}else{
		layer.alert('确定要删除这'+selectArray.length+'项吗？',{
			time:0,
			btn:['确定','取消'],
			yes:function (index) {
				var dataArray = [];
				for(var i = 0 ; i < selectArray.length ;  i++ ){
					var object = selectArray[i];
					dataArray.push(object.FCODE);
				}
				$.ajax({
					type:'post',
					url:tsUtils.getRootPath()+'/user/deleteUser',
					data:JSON.stringify(dataArray),
					contentType:'application/json;charset=utf-8',
					success:function (data) {
						if(data.msg == null){
							$('#postTable').bootstrapTable('refresh'
								,{
									url:tsUtils.getRootPath()+'/user/deleteUser'
									,contentType:"application/x-www-form-urlencoded",
									queryParams:function (params) {
										params["where"]=sysObj.deptCode;
										return params;
									}
								});
							layer.close(index);
							layer.msg('删除成功',{time:1500});
						}else{
							layer.close(index);
							layer.msg('删除失败',{time:1500});
						}
					},
					error:function (data) {

					}
				});
			}
		})
	}
}

//打印岗位
function printUser() {
	tableUtils.init('userTable');
	tableUtils.doPrint();
}

//导出岗位
function exportUser() {
	tableUtils.init('userTable');
	tableUtils.exportTableToExcel(0);
}

//退出iframe
function exitFrame() {
	tsUtils.removeIframe();
}

//修改密码
function editPassword() {
	$('#edit-password form')[0].reset();
	$('#edit-password form :input').attr('value','');
	layer.open({
		type:1,
		title:'用户-修改密码',
		area:['400px','250px'],
		skin:'layer-window',
		shadeClose:true,
		content:$('#edit-password'),
		btn:['修改','取消'],
		yes:function () {
			var data = sysForm.getFormData('editPassword');
			console.log(data);
		}
	})
}

/*设置岗位*/
function setPost(){
	var selectArray;
	selectArray = $('#userTable').bootstrapTable('getSelections');
	if(selectArray.length == 0){
		layer.alert('请选择用户');
		return
	}else if(selectArray.length > 1){
		layer.alert('不能同时设置多个用户');
		return
	}

	var usercode = selectArray[0].FCODE;


	var settings = {
		url			:tsUtils.getRootPath()+'/user/getDeptPost',
		method		:'post',
		striped		:true,					//是否显示间隔栏颜色
		pagination	:true,					//是否分页
		sortable	:false,					//是否启用排序
		pageSize	:5,
		pageList	:[5,10,15,20],
		contentType:"application/x-www-form-urlencoded",
		height		:400,
		columns		:[{
			field:'FROWNUM',
			title:'序号',
			align:'center',
			width:40
		},{
			title:'选中',
			field:'state',
			checkbox:true,
			formatter:function (value,row,index) {
				var postData = {};
				postData.usercode = usercode;
				var array = [];
				$.ajax({
					type: 'post',
					async:false,
					url: tsUtils.getRootPath() + "/user/getUserPostList",
					data: JSON.stringify(postData),
					contentType: 'application/json;charset=utf-8',
					success: function (datas) {
						array = datas.rows;
					}
				});
				var flag = false;
				for(var i = 0 ; i < array.length; i ++){
					if(row.FCODE == array[i].FPOSTCODE){
						flag = true;
						break;
					}
				}
				if(flag){
					return {checked:true};
				}else {
					return value;
				}
			}
		},{
			field:'FCODE',
			title:'岗位代码',
			align:'center',
			width:60
		},{
			field:'FNAME',
			title:'岗位名称',
			align:'center',
			width:60,

		},{
			field:'FISSTOP',
			title:'是否停用',
			width:20,
			align:'center'
		}],
		queryParams :function (params) {
			params['usercode'] = usercode;
			return params;
		},
		onLoadError:function (data) {
			tsUtils.handleError(data);
		}
	};

	layer.open({
		type:1,
		title:'设置岗位',
		area:['600px','550px'],
		skin:'layer-window',
		shadeClose:true,
		content:$('#setPost'),
		btn:['修改','取消'],
		success:function(){
			$('#postTable').bootstrapTable(settings);
		},
		yes:function () {
			var postArray = $('#postTable').bootstrapTable('getSelections');
			var postCodeArray = [];
			for(var i = 0 ; i < postArray.length ; i++){
				postCodeArray.push(postArray[i].FCODE);
			}
			var postData = {};
			postData.usercode = usercode;
			postData.postCodeArray = postCodeArray;


			$.ajax({
				type:'post',
				url:tsUtils.getRootPath()+'/user/setUserPost',
				data:JSON.stringify(postData),
				contentType:'application/json;charset=utf-8',
				success:function (data) {
					layer.closeAll();
					layer.msg('设置成功', {time: 1500});
				},
				error:function (data) {

				}
			});

		}
	})
}